package com.example.managemyself.api.repository;

import com.example.managemyself.api.entity.HealthData;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

/**
 * 健康数据访问接口
 */
@Repository
public interface HealthDataRepository extends JpaRepository<HealthData, Integer> {
    
    /**
     * 根据用户ID查找所有健康数据
     */
    List<HealthData> findByUserIdOrderByRecordDateDesc(Integer userId);
    
    /**
     * 根据用户ID和记录日期查找健康数据
     */
    Optional<HealthData> findByUserIdAndRecordDate(Integer userId, LocalDate recordDate);
    
    /**
     * 查找用户在指定日期范围内的健康数据
     */
    @Query("SELECT h FROM HealthData h WHERE h.userId = :userId AND h.recordDate BETWEEN :startDate AND :endDate ORDER BY h.recordDate DESC")
    List<HealthData> findByUserIdAndDateRange(@Param("userId") Integer userId, 
                                             @Param("startDate") LocalDate startDate, 
                                             @Param("endDate") LocalDate endDate);
    
    /**
     * 查找用户最近N天的健康数据
     */
    @Query("SELECT h FROM HealthData h WHERE h.userId = :userId AND h.recordDate >= :startDate ORDER BY h.recordDate DESC")
    List<HealthData> findRecentHealthData(@Param("userId") Integer userId, @Param("startDate") LocalDate startDate);
    
    /**
     * 查找用户最新的健康数据
     */
    Optional<HealthData> findTopByUserIdOrderByRecordDateDesc(Integer userId);
    
    /**
     * 查找用户有体重记录的数据
     */
    @Query("SELECT h FROM HealthData h WHERE h.userId = :userId AND h.weight IS NOT NULL ORDER BY h.recordDate DESC")
    List<HealthData> findByUserIdWithWeight(@Param("userId") Integer userId);
    
    /**
     * 查找用户有睡眠记录的数据
     */
    @Query("SELECT h FROM HealthData h WHERE h.userId = :userId AND h.sleepHours IS NOT NULL ORDER BY h.recordDate DESC")
    List<HealthData> findByUserIdWithSleep(@Param("userId") Integer userId);
    
    /**
     * 查找用户有步数记录的数据
     */
    @Query("SELECT h FROM HealthData h WHERE h.userId = :userId AND h.stepsCount IS NOT NULL ORDER BY h.recordDate DESC")
    List<HealthData> findByUserIdWithSteps(@Param("userId") Integer userId);
    
    /**
     * 统计用户健康数据记录天数
     */
    long countByUserId(Integer userId);
    
    /**
     * 检查用户在指定日期是否已有记录
     */
    boolean existsByUserIdAndRecordDate(Integer userId, LocalDate recordDate);
} 